import 'nprogress/nprogress.css';

import axios from 'axios';
import NProgress from 'nprogress';

import useUserStore from '../store/modules/user';

const request = axios.create({
  timeout: 5000,
  baseURL: '/api',
});

request.interceptors.request.use((config) => {
  NProgress.start();
  const userStore = useUserStore();
  if (userStore.token) {
    config.headers.Authorization = userStore.token;
  }
  if (localStorage.getItem('token')) {
    config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
    config.headers.id = localStorage.getItem('id');
  }
  return config;
});

request.interceptors.response.use(
  (response) => {
    NProgress.done();
    return response.data;
  },
  (err) => {
    console.log(err);
  },
);

export default request;
